import Vue from "vue";

const numFormate = (value, formateConfig = {}) => {
    let {
        smallNum = 2,
        ratio = 1,
        startUnit = "",
        endUnit = "",
        nullValue = "-",
    } = formateConfig;
    if (!Number(value) && value != 0) {
        return nullValue;
    }
    const number = value * ratio;
    const newNumber = `${number}`.replace(/[^0-9+-Ee.]/g, "");
    const n = !Number.isFinite(+newNumber) ? 0 : +newNumber;
    const prec = !Number.isFinite(+smallNum) ? 0 : Math.abs(smallNum);
    let s = "";
    const toFixedFix = function (nPar, precPar) {
        const k = 10 ** precPar;
        return `${
            parseFloat(
                Math.round(parseFloat((nPar * k).toFixed(precPar * 2))).toFixed(
                    precPar * 2
                )
            ) / k
        }`;
    };
    s = (prec ? toFixedFix(n, prec) : `${Math.round(n)}`).split(".");
    const re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, `$1${","}$2`);
    }

    if ((s[1] || "").length < prec) {
        s[1] = s[1] || "";
        s[1] += new Array(prec - s[1].length + 1).join("0");
    }
    return `${startUnit}${s.join(".")}${endUnit}`;
};

//利率过滤，小数位大于两位不加0，小于两位补0，为空不处理
const rateFormate = (value, addSymbol = "") => {
    if (value == "" || value == null || value == undefined) return value;
    let str = value.toString();
    let rateString = value.toString().indexOf(".");
    let rateLength = value.toString().length;
    //无小数点
    if (rateString < 0) {
        return str + ".00" + addSymbol;
    }
    //大于等于两位小数不加0
    if (rateString + 3 <= rateLength) {
        return value + addSymbol;
    }
    //小于两位小数的补0
    // eslint-disable-next-line for-direction
    for (let i = rateLength; i > rateString + 1; i--) {
        str += "0";
    }
    return str + addSymbol;
};

Vue.filter("numFormate", numFormate);
Vue.filter("rateFormate", rateFormate);

const dateFormate = (value, formate = "YYYY-MM-DD") => {
    if (value) {
        let dateObj;
        switch (Object.prototype.toString.call(value)) {
            case "[object Number]":
                dateObj = new Date(value);
                break;
            case "[object String]":
                value = value.replace(/-/g, "/"); //ie 不支持 '2018-11-11 00:01:01' 这样的写法 Invalid Date;
                dateObj = new Date(value);
                break;
            case "[object Date]":
                dateObj = value;
                break;
            default:
                console.warn(
                    "[dateFormate error]value:",
                    value,
                    Object.prototype.toString.call(value)
                );
                return value;
        }

        if (isNaN(dateObj.getTime())) {
            //说明是 Invalid Date
            return value;
        }

        const year = dateObj.getFullYear();
        const month =
            Number(dateObj.getMonth() + 1) > 9
                ? String(dateObj.getMonth() + 1)
                : "0" + String(dateObj.getMonth() + 1);
        const day =
            Number(dateObj.getDate()) > 9
                ? String(dateObj.getDate())
                : "0" + String(dateObj.getDate());
        const hour =
            Number(dateObj.getHours()) > 9
                ? String(dateObj.getHours())
                : "0" + String(dateObj.getHours());
        const minute =
            Number(dateObj.getMinutes()) > 9
                ? String(dateObj.getMinutes())
                : "0" + String(dateObj.getMinutes());
        const second =
            Number(dateObj.getSeconds()) > 9
                ? String(dateObj.getSeconds())
                : "0" + String(dateObj.getSeconds());

        formate = formate.replace(/Y{1,4}/i, year);
        formate = formate.replace(/M{1,2}/, month);
        formate = formate.replace(/D{1,2}/i, day);
        formate = formate.replace(/H{1,2}/i, hour);
        formate = formate.replace(/m{1,2}/, minute);
        formate = formate.replace(/S{1,2}/i, second);

        return formate;
    } else {
        return value;
    }
};

Vue.filter("dateFormate", dateFormate);

/**
 * 字符串添加星号遮掩
 * @param {*} val 字符串
 * @param {*} front 前面多少位
 * @param {*} back 后面面多少位
 */
const coverString = function (val = "", front = 3, back = 4) {
    if (
        !val ||
        String(val).length < front + back ||
        isNaN(front) ||
        isNaN(back)
    )
        return "****";
    return (
        val.substring(0, front) +
        "*".repeat(val.length - back - front) +
        val.substring(val.length - back)
    );
};

Vue.filter("coverString", coverString);

const keepNumber = function (value) {
    //过滤器保留4为小数
    const numM = Number(value).toFixed(5);
    if (numM === "NaN") {
        return "0.0000";
    }
    const realVal = numM.substring(0, numM.length - 1);
    return realVal;
};

Vue.filter("filterDic", function (value, valueName = "displayName") {
    if (value) {
        try {
            return JSON.parse(value)[valueName];
        } catch (e) {
            return value;
        }
    }
});

Vue.filter("keepNumber", keepNumber);
//手机号脱敏
const maskPhoneNumber = function (path) {
    if (path != undefined && path != "")
        return path.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
};
Vue.filter("maskPhoneNumber", maskPhoneNumber);
//身份证脱敏
const IDcard = function (path) {
    if (path != undefined && path != "") {
        const reg = /^(.{3})(?:\d+)(.{2})$/; // 匹配身份证号前6位和后4位的正则表达式
        const maskedIdCard = path.replace(reg, "$1*************$2");
        return maskedIdCard;
    }
};
Vue.filter("IDcard", IDcard);
//姓名脱敏
const noPassByName = function (str) {
    if (null != str && str != undefined) {
        if (str.length == 2) {
            return str.substring(0, 1) + "*"; //截取name 字符串截取第一个字符，
        } else if (str.length == 3) {
            return str.substring(0, 1) + "*" + str.substring(2, 3); //截取第一个和第三个字符
        } else if (str.length > 3) {
            return str.substring(0, 1) + "*" + str.substring(2, str.length); //截取第一个和大于第4个字符
        }
    } else {
        return "";
    }
};
Vue.filter("noPassByName", noPassByName);
//地址脱敏
const addressNumber = function (address) {
    if (address != undefined && address != "") {
        address = address.slice(0, -4) + "****";
    }
    return address;
};
Vue.filter("addressNumber", addressNumber);
//邮箱脱敏
const noPassByEmail = function (email) {
    if (email == null) {
        return email;
    }
    const parts = email.split("@");
    const name = parts[0];
    const domain = parts[1];

    // 保留第一个和最后一个字符，其余部分用星号代替
    const desensitizedName =
        name.charAt(0) + "****" + name.charAt(name.length - 1);

    return desensitizedName + "@" + domain;
};
Vue.filter("noPassByEmail", noPassByEmail);
export default {
    numFormate,
    rateFormate,
    keepNumber,
    maskPhoneNumber, //手机号脱敏
    IDcard, //身份证脱敏
    noPassByName, //姓名脱敏
    addressNumber, //地址脱敏
    noPassByEmail, //邮箱脱敏
};
